#!/bin/env python

#
# Execute a single Howl command.
#
#
# Usage:
#
# $ python howl.py --help
# Usage: howl.py [options]
#
# Options:
#   -h, --help            show this help message and exit
#   -e EMAIL, --email=EMAIL
#                         Your Google mail address
#   -p PASSWORD, --password=PASSWORD
#                         Your Google mail password
#   -c COMMAND, --command=COMMAND
#                         Howl command to execute
# $ 
#
#
# Uses Dale Lane's Python script from: http://dalelane.co.uk/blog/?p=303
#

import os
import urllib
import urllib2
import cookielib


__author__ = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__ = '21 November 2009'
__credits__ = 'Dale Lane http://dalelane.co.uk'


baseurl = 'http://uowapplication.appspot.com/'
target_authenticated_google_app_engine_uri = baseurl + 'api'
my_app_name = "uowapplication"


def authenticate(users_email_address, users_password):
    """Authenticate a Google service user and return an authentication token.
    """

    # We use a cookie to authenticate with Google App Engine
    # by registering a cookie handler here, this will automatically store the
    # cookie returned when we use urllib2 to open
    # http://uowapplication.appspot.com/_ah/login
    cookiejar = cookielib.LWPCookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
    urllib2.install_opener(opener)

    # Get an AuthToken from Google accounts
    auth_uri = 'https://www.google.com/accounts/ClientLogin'
    authreq_data = urllib.urlencode({ "Email":   users_email_address,
                                      "Passwd":  users_password,
                                      "service": "ah",
                                      "source":  my_app_name,
                                      "accountType": "HOSTED_OR_GOOGLE" })
    auth_req = urllib2.Request(auth_uri, data=authreq_data)
    auth_resp = urllib2.urlopen(auth_req)
    auth_resp_body = auth_resp.read()
    # auth response includes several fields - we're interested in
    #  the bit after Auth=
    auth_resp_dict = dict(x.split("=")
                          for x in auth_resp_body.split("\n") if x)
    authtoken = auth_resp_dict["Auth"]
    return authtoken


def run_command(email, password, command):
    """Run a Howl command with given user authentication.
    """
    authtoken = authenticate(email, password)

    # this is where I actually want to go to
    serv_uri = (target_authenticated_google_app_engine_uri +
                "?command=" + command)

    serv_args = {'continue':serv_uri, 'auth':authtoken}

    full_serv_uri = baseurl + "_ah/login?%s" % (urllib.urlencode(serv_args))

    serv_req = urllib2.Request(full_serv_uri)
    serv_resp = urllib2.urlopen(serv_req)
    serv_resp_body = serv_resp.read()

    if serv_resp_body == '':
        print 'Howl command executed successfully.'
   


if __name__ == '__main__':

    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option('-e', '--email', dest='email', 
                      action='store', type='string',
                      help='Your Google mail address')    
    parser.add_option('-p', '--password', dest='password', 
                      action='store', type='string',
                      help='Your Google mail password')    
    parser.add_option('-c', '--command', dest='command', 
                      action='store', type='string',
                      help='Howl command to execute')    

    (options, args) = parser.parse_args()
    
    run_command(options.email, options.password, options.command)

